#include <Windows.h>
#include <tchar.h>
#include "resource.h"

int CALLBACK DlgProc(HWND hDlg, UINT nMsg, WPARAM wParam, LPARAM lParam)
{
	switch (nMsg)
	{
		case WM_INITDIALOG:
		{			
			SetWindowText(hDlg, _T("Demo0067"));
			UINT nWidth		= GetSystemMetrics(SM_CXSCREEN);
			UINT nHeight	= GetSystemMetrics(SM_CYSCREEN);
			RECT rtWindow;
			GetWindowRect(hDlg, &rtWindow);
			int  nLeft		= (nWidth - (rtWindow.right - rtWindow.left)) / 2;
			int  nRight		= (nHeight - (rtWindow.bottom - rtWindow.top)) / 2;
			SetWindowPos(hDlg, NULL, nLeft, nRight, 0, 0, SWP_NOSIZE);

			break;
		}
		case WM_COMMAND:
		{
			switch (LOWORD(wParam))
			{
				case IDC_BTNVIEW:
				{
					TCHAR szQuery[MAX_PATH];
					TCHAR szFormat[MAX_PATH];
					GetDlgItemText(hDlg, IDC_EDTFORMAT, szFormat, MAX_PATH);
					if (NULL != *szFormat)
					{
						TCHAR* szPos = _tcsrchr(szFormat, _T('.'));
						if (NULL == szPos)
						{
							_tcscpy(szQuery, _T("."));
							_tcscat(szQuery, szFormat);
						} else {
							_tcscpy(szQuery, szPos);
						}
					}
					
					HKEY hSubKey;
					if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_CLASSES_ROOT, szQuery, 0, KEY_ALL_ACCESS, &hSubKey))
					{
						TCHAR szType[MAX_PATH] = _T("Unknow format");
						LONG dwDataSize = sizeof(TCHAR) * MAX_PATH;
						if (ERROR_SUCCESS == RegQueryValue(hSubKey, NULL, (LPTSTR)szType, &dwDataSize))
						{
							HKEY hSubKey2;
							TCHAR szQuery2[MAX_PATH];
							TCHAR szPath[MAX_PATH] = _T("Can't query this type's path");
							LONG dwDataSize2 = sizeof(TCHAR) * MAX_PATH;
							_tcscpy(szQuery2, szType);
							_tcscat(szQuery2, _T("\\shell\\open\\command"));
							if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_CLASSES_ROOT, szQuery2, 0, KEY_ALL_ACCESS, &hSubKey2))
							{
								RegQueryValue(hSubKey2, NULL, szPath, &dwDataSize2);
							}
							SetDlgItemText(hDlg, IDC_STCPATH, szPath);	
						}

						RegCloseKey(hSubKey);

						SetDlgItemText(hDlg, IDC_STCTYPE, szType);						
						
						TCHAR szTmpType[MAX_PATH];
						_stprintf(szTmpType, _T("test.%s"), szFormat);
				
						SHFILEINFO shfi = {0};
						SHGetFileInfo(szTmpType, FILE_ATTRIBUTE_NORMAL, &shfi, sizeof(shfi), SHGFI_ICON|SHGFI_USEFILEATTRIBUTES);
						
						//_tcscpy(szTmpType, _T("F:\\zTercelStudio\\DemoProjects\\ProjectsNotes.xls"));
						//SHGetFileInfo(szTmpType, FILE_ATTRIBUTE_NORMAL, &shfi, sizeof(shfi), SHGFI_EXETYPE);
						
						SendMessage(GetDlgItem(hDlg, IDC_STCICON), STM_SETICON, (LPARAM)shfi.hIcon, 0);	
						DestroyIcon(shfi.hIcon);
					}

					break;
				}
			}

			break;
		}

		case WM_CLOSE:
		{
			PostQuitMessage(0);
			break;
		}
	}

	return 0;
}

BOOL WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPreInstance, LPTSTR szCmdLine, int nShowCmd)
{
	DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG), NULL, DlgProc);
	return 0;
}